<template>
  <div class="">
    <van-swipe-cell
      v-for="(item, index) in $store.state.shopcar"
      :key="item._id"
    >
      <van-row>
        <van-col span="4">
          <input type="checkbox" v-model="res" :value="item" @change="changes"
        /></van-col>
        <!-- 原生的checkbox 应该使用change事件 就没有bug -->
        <van-col span="20">
          <van-card
            :num="item.num"
            :price="item.price"
            :title="item.title"
            :thumb="item.pic"
          >
            <template #footer>
              <van-stepper v-model="item.num" @change="change" />
            </template>
          </van-card>
        </van-col>
      </van-row>

      <template #right>
        <van-button
          square
          text="删除"
          type="danger"
          class="delete-button"
          @click="del(item._id)"
        />
      </template>
    </van-swipe-cell>

    <van-button type="primary" @click="remove">选中删除</van-button>

    <van-submit-bar :price="sum * 100" button-text="提交订单">
      <van-checkbox v-model="checked" @click="checkall">全选</van-checkbox>
      <!-- 不是原生的checkbox 就用点击事件 -->
    </van-submit-bar>
  </div>
</template>

<script>
export default {
  data() {
    return {
      checked: false,
      //全选按钮是否选中
      res: [],
      //复选框组选中的内容
    };
  },
  mounted() {},
  methods: {
    del(id) {
      this.$store.commit("del", id);
      this.res.forEach((item, index) => {
        if (item._id == id) {
          this.res.splice(index, 1);
        }
      });
    },
    changes() {
      console.log(111);
      if (this.$store.state.shopcar.length == this.res.length) {
        this.checked = true;
      } else {
        this.checked = false;
      }
    },
    //点击 购物车商品前面的复选框触发 判断的是 购物车的数量和选中的数量是否一致 就让全选按钮为true
    checkall() {
      if (this.checked == true) {
        this.res = this.$store.state.shopcar;
      } else {
        this.res = [];
      }
    },
    //给全选按钮绑定的事件  如果全选了 就让res等于购物车

    remove() {
      this.$store.commit("remove", this.res);
      //把要删的数组传参传至vuex 在vuex里实现选中删除
    },
    change() {
      this.$store.commit("change");
    },
  },
  components: {},
  computed: {
    sum() {
      let num = 0;
      this.res.forEach((item) => {
        num += item.price * item.num;
      });
      return num;
    },
  },
};
</script>

<style lang="scss">
.delete-button {
  height: 100%;
}
.van-row {
  display: flex;
  align-items: center;
}
.van-submit-bar {
  bottom: 50px !important;
}
</style>
